package offer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import system.bean.AuditModuleItem;
import system.bean.DocRelation;
import system.bean.Member;
import system.bean.ModuleDocument;
import system.bean.ModuleFile;
import system.dao.AuditModuleItemDao;
import system.dao.DocRelationDao;
import system.dao.DocumentDao;
import util.PageList;


public class DocDataSource {
	private static DocumentDao documentDao = new DocumentDao();
	private static DocRelationDao relationDao = new DocRelationDao();
	private static AuditModuleItemDao auditItemDao = new AuditModuleItemDao();
	/**
	 * get member information from session
	 * @param request
	 * @return
	 */
	private static Member getSessionMember(HttpServletRequest request){
		Member member = null;
		
		try {
			SessionObj sessionObj = (SessionObj)request.getSession().getAttribute("sessionObj");
			member = sessionObj.getMember();
		} catch (Exception e) {
		}
		return member;
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	public static ArrayList<ModuleDocument> getUserDocList(HttpServletRequest request){
		//1��module��importΪ0����û�й�j�����ļ������
		ArrayList<ModuleDocument> docList = null;
		Member member = getSessionMember(request);
		docList = documentDao.getDocmentListByMemberId(member.getMemberId());
		
		return docList;
	}
	
	public static ArrayList<String> getUserMainModules(HttpServletRequest request){
		ArrayList<String>  moduleNames = new ArrayList<String>();
		
		ArrayList<ModuleDocument> docList = null;
		ModuleDocument            document= null;
		docList = getUserDocList(request);
		Iterator<ModuleDocument> iterator = docList.iterator();
		while (iterator.hasNext()) {
			document = iterator.next();
			if("MainModule".equalsIgnoreCase(document.getDocType())){
				moduleNames.add(document.getDocName());
			}
		}
		return moduleNames;
	}
	
	public static ModuleDocument getUserDocumentByName(HttpServletRequest request , String moduleName){
		ModuleDocument document = null;
		Member member = getSessionMember(request);;
		document = documentDao.getMemberDocument(member.getMemberId(), moduleName);
		
		return document;
	}
	
	public static ModuleDocument getDocumentBydocId( int docId){
		ModuleDocument document = null;
		document = documentDao.getDocumentByID(docId);
		
		return document;
	}
	
	public static ArrayList<ModuleDocument> getPageList(HttpServletRequest request , PageList pageBean)throws ServletException, IOException{
		if(null == pageBean) return null;
		ArrayList<ModuleDocument> docList = null;
		Member member = getSessionMember(request);
		
		String isPaging=request.getParameter("isPaging");
		int totalItems = 0;
		if(isPaging!=null&&isPaging.equalsIgnoreCase("Y")){
	    	int iPageNo = Integer.valueOf(request.getParameter("iPageNo"));
	    	totalItems = Integer.valueOf(request.getParameter("totalItem"));
	    	pageBean.setCurrentPage(iPageNo);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    }else{
	    	totalItems = documentDao.getTotalItemsByMemberId(member.getMemberId());
	    	pageBean.setCurrentPage(1);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    	
	    }
		pageBean.CalculatePageNoInfo();
		String sql = "select docId,memberId,docName,displayName,docType,status,ipPublic,belongsTo,dependFileIds from moduledocument where memberId = "+member.getMemberId()+
		" limit "+pageBean.getStart()+", "+pageBean.getPageSize();
		
		docList = documentDao.getPageListByQuerySQL(sql);
		
		return docList;
	}
	
	public static ArrayList<ModuleDocument> getUnAuditPageList(HttpServletRequest request , PageList pageBean)throws ServletException, IOException{
		if(null == pageBean) return null;
		ArrayList<ModuleDocument> docList = null;
		Member member = getSessionMember(request);
		
		String isPaging=request.getParameter("isPaging");
		int totalItems = 0;
		if(isPaging!=null&&isPaging.equalsIgnoreCase("Y")){
	    	int iPageNo = Integer.valueOf(request.getParameter("iPageNo"));
	    	totalItems = Integer.valueOf(request.getParameter("totalItem"));
	    	pageBean.setCurrentPage(iPageNo);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    }else{
	    	totalItems = auditItemDao.getUnauditedTotalItemsByMemberId(member.getMemberId());
	    	pageBean.setCurrentPage(1);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    	
	    }
		pageBean.CalculatePageNoInfo();
		//****************************************************
		ArrayList<Object> unaduitList = auditItemDao.getUnauditedListByMemberId(member.getMemberId());
		String audit_docIds = "";
		AuditModuleItem auditItem = null;
		for(int i = 0 ; i < unaduitList.size() ; i++){
			auditItem = (AuditModuleItem)unaduitList.get(i);
			audit_docIds += auditItem.getDocId()+",";
		}
		if(audit_docIds.length()>0){
			audit_docIds = audit_docIds.substring(0, audit_docIds.length()-1);
		}else{
			audit_docIds = "0";
		}
		//****************************************************
		String sql = "select docId,memberId,docName,displayName,docType,status,ipPublic,belongsTo,dependFileIds from moduledocument where docId in ("+audit_docIds+
		") limit "+pageBean.getStart()+", "+pageBean.getPageSize();
		
		docList = documentDao.getPageListByQuerySQL(sql);
		
		return docList;
	}
	
	public static ArrayList<ModuleDocument> getAuditedPageList(HttpServletRequest request , PageList pageBean)throws ServletException, IOException{
		if(null == pageBean) return null;
		ArrayList<ModuleDocument> docList = null;
		Member member = getSessionMember(request);
		
		String isPaging=request.getParameter("isPaging");
		int totalItems = 0;
		if(isPaging!=null&&isPaging.equalsIgnoreCase("Y")){
	    	int iPageNo = Integer.valueOf(request.getParameter("iPageNo"));
	    	totalItems = Integer.valueOf(request.getParameter("totalItem"));
	    	pageBean.setCurrentPage(iPageNo);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    }else{
	    	totalItems = auditItemDao.getAuditedTotalItemsByMemberId(member.getMemberId());
	    	pageBean.setCurrentPage(1);
	    	pageBean.setTotalItems(totalItems);
	    	pageBean.setPageSize(5);
	    	
	    }
		pageBean.CalculatePageNoInfo();
		//****************************************************
		ArrayList<Object> aduitedList = auditItemDao.getAuditedListByMemberId(member.getMemberId());
		String audit_docIds = "";
		AuditModuleItem auditItem = null;
		for(int i = 0 ; i < aduitedList.size() ; i++){
			auditItem = (AuditModuleItem)aduitedList.get(i);
			audit_docIds += auditItem.getDocId()+",";
		}
		if(audit_docIds.length()>0){
			audit_docIds = audit_docIds.substring(0, audit_docIds.length()-1);
		}else{
			audit_docIds = "0";
		}
		//****************************************************
		String sql = "select docId,memberId,docName,displayName,docType,status,ipPublic,belongsTo,dependFileIds from moduledocument where docId in ("+audit_docIds+
		") limit "+pageBean.getStart()+", "+pageBean.getPageSize();
		
		docList = documentDao.getPageListByQuerySQL(sql);
		
		return docList;
	}
	
	public static boolean isExitIncludeRelation(int mainDocID , int relyDocID){
		boolean flag = false;
		flag = relationDao.isExitSomeRelation(mainDocID, relyDocID, "include");
		return flag;
	}
	
	public static boolean isExitImportRelation(int mainDocID , int relyDocID){
		boolean flag = false;
		flag = relationDao.isExitSomeRelation(mainDocID, relyDocID, "import");
		return flag;
	}
	
	public static boolean addIcludeRelation(int mainDocID , int relyDocID){
		boolean flag = false;
		DocRelation relation = new DocRelation();
		relation.setMainDocId(mainDocID);
		relation.setRelatedDocId(relyDocID);
		relation.setRelationType("include");
		flag = relationDao.insert(relation);
		return flag;
	}
	
	public static boolean addImportRelation(int mainDocID , int relyDocID){
		boolean flag = false;
		DocRelation relation = new DocRelation();
		relation.setMainDocId(mainDocID);
		relation.setRelatedDocId(relyDocID);
		relation.setRelationType("import");
		flag = relationDao.insert(relation);
		return flag;
	}
	public static void removeRelation(DocRelation relation){
		relationDao.delete(relation);
	}
	
	/**
	 * Map<DocRelation, Integer>  is Map<DocRelation,idDelete> idDelete = 0 ��ʾ�ù�ϵ�Ѿ������� ��ɾ��
	 * @param mainDocID
	 * @return
	 */
	public static Map<DocRelation, Integer> getRelationMap(int mainDocID){
		Map<DocRelation, Integer>  relationMap  = new HashMap<DocRelation, Integer>(); 
		ArrayList<DocRelation> relationList = relationDao.getListByMainDocID(mainDocID);
		
		Iterator<DocRelation> it = relationList.iterator();
		
		while(it.hasNext()){
			relationMap.put(it.next(), 0);
		}
		return relationMap;
	}
	
	public static String DeleteDocument(int docId){
		String msg ="Success";
		ArrayList<DocRelation> relationList = relationDao.getListByRelayDocID(docId);
		if(relationList.size() > 0){
			msg ="Failed to delete this document, it's related by other documents.";
			return msg;
		}
		
		//ɾ����ļ�����5��ϵ
		relationList = relationDao.getListByMainDocID(docId);
		Iterator<DocRelation> it = relationList.iterator();
		while(it.hasNext()){
			relationDao.delete(it.next());
		}
		//ɾ����ļ�
		documentDao.delete(docId);
		return msg;
	}
	
	public static boolean updateDependFileIds(int docId,int fileId){
		ModuleDocument document = getDocumentBydocId(docId);
		String dependFileIds =null;
		if(null == document.getDependFileIds() || document.getDependFileIds().equalsIgnoreCase("")){
			dependFileIds = ""+fileId;
		}else{
			dependFileIds = document.getDependFileIds() +","+fileId;
		}
		document.setDependFileIds(dependFileIds);
		return documentDao.update(document);
	}
	
}
